package org.three;

import java.io.*;
import java.net.*;

/**
 * Created by Administrator on 2016/3/14 0014.
 */
public class FileServer {
    public static void main(String[] args) throws IOException {
        // 设定服务器，并侦听7777端口
        ServerSocket server = new ServerSocket(7777);
        int i = 0;
        while ( i < 10 ) {
            i++;
            Socket client = server.accept();        // 阻塞并等待客户端连接
            new Thread(new FileServerThread(client)).start();
        }
    }
}

class FileServerThread implements Runnable {
    private Socket client ;

    public FileServerThread( Socket client ) {
        this.client = client;
    }

    @Override
    public void run() {
        String dir = System.getProperty("user.dir");
        String s = File.separator;

        System.out.println("有新的客户端连接：" + client.getInetAddress() + ":" + client.getPort() + ")");

        synchronized (this) {
            try (InputStream fis = new FileInputStream(dir + s + "new.mp4");) {

                OutputStream fos = client.getOutputStream();

                byte[] b = new byte[1024];
                int count = 0;
                while ((count = fis.read(b)) != -1) {
                    fos.write(b, 0, count);       // 写入到网络流
                }
                System.out.println("文件传送完毕...");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}